package com.wenhai.spring.dependency.lookup;

import com.wenhai.xiaomage.spring.ioc.overview.dependency.domain.User;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @Author:wenhai
 * @Description: 安全依赖查找
 * @Date:2020/3/9
 */
public class TypeSafetyDependencyLookupDemo {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        ctx.register(TypeSafetyDependencyLookupDemo.class);
        ctx.refresh();
        displayBeanFactoryGetBean(ctx);
        displayObjectFactoryGetObject(ctx);
        displayObjectProviderIfAvailable(ctx);
        displayListableBeanGetBeansOfType(ctx);
        ctx.close();
    }

    private static void displayListableBeanGetBeansOfType(ListableBeanFactory beanFactory) {
        printBeanException(() -> beanFactory.getBeansOfType(User.class), "listableBeanFactory");
    }

    private static void displayBeanFactoryGetBean(BeanFactory beanFactory) {
        printBeanException(() -> beanFactory.getBean(User.class), "beanFactory");
    }

    private static void displayObjectFactoryGetObject(BeanFactory beanFactory) {
        printBeanException(() -> {
            ObjectFactory<User> beanProvider = beanFactory.getBeanProvider(User.class);
            User object = beanProvider.getObject();
        }, "ObjectFactory");
    }

    private static void displayObjectProviderIfAvailable(BeanFactory beanFactory) {
        printBeanException(() -> {
            ObjectProvider<User> beanProvider = beanFactory.getBeanProvider(User.class);
            User object = beanProvider.getIfAvailable();
        }, "ObjectProvider");
    }

    public static void printBeanException(Runnable runnable, String message) {
        try {
            runnable.run();
        } catch (BeansException e) {
            System.out.println(message + "发生异常");
            e.printStackTrace();
        }
    }
}
